#include <stdio.h>
#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "driver/gpio.h"

#include "lvgl.h"
#include "demos/lv_demos.h" 
#include "ui.h"    // 替换为你的 ui头文件

#include "lcd_st7789.h"     // 显示驱动
#include "controller.h"     // 控制驱动


static const char *TAG = "use_demo";


static lv_disp_drv_t disp_drv;
static lv_indev_drv_t indev_drv;
static lv_indev_t *input_device;


/**
 * @brief lvgl时钟心跳回调函数
 */
static void lv_tick_task_cb(void *arg){
    lv_tick_inc(1);
}


/**
 * @brief lvgl初始化示例函数（默认显示内容为benchmark示例）
 */
static esp_err_t lvgl_init_demo(void){
    // Initialize LVGL display device
    lcd_st7789_init(&disp_drv);
    lv_init();
    // alloc draw buffers used by LVGL
    lv_color_t *buf1 = NULL;
    lv_color_t *buf2 = NULL;
    buf1 = heap_caps_malloc(LCD_H_RES * 100 * sizeof(lv_color_t), MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
    assert(buf1);
    buf2 = heap_caps_malloc(LCD_H_RES * 100 * sizeof(lv_color_t), MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
    assert(buf2);
    // initialize LVGL draw buffers
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf1, buf2, LCD_H_RES * 100);
    lv_disp_drv_init(&disp_drv);
    disp_drv.hor_res = LVGL_H_PIXEL;
    disp_drv.ver_res = LVGL_V_PIXEL;
    disp_drv.flush_cb = disp_flush_cb;
    disp_drv.draw_buf = &disp_buf;
    disp_drv.user_data = panel_handle;
    // disp_drv.offset_x = 20;     // 调整x轴偏移补偿横屏显示
    // disp_drv.offset_y = 20;     // 调整y轴偏移补偿横屏显示、
    lv_disp_drv_register(&disp_drv);
    ESP_LOGI(TAG, "LVGL dispaly driver ready");

    // Tick interface for LVGL (using esp_timer to generate 1ms periodic event)
    const esp_timer_create_args_t lvgl_tick_timer_args = {
        .callback = &lv_tick_task_cb,
        .name = "lvgl_tick"};
    esp_timer_handle_t lvgl_tick_timer = NULL;
    ESP_ERROR_CHECK(esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer));
    ESP_ERROR_CHECK(esp_timer_start_periodic(lvgl_tick_timer, 1 * 1000));
    ESP_LOGI(TAG, "LVGL tick timer ready");

    // load ui & blk
    // lv_demo_benchmark();    // 在此替换为你的 ui初始化函数
    ui_init();

#if LCD_BLK_PWM_CTRL
    lcd_set_brightness(LCD_DEFAULT_BRIGHTNESS); // 开启背光
#endif  

    // Initialize the input device
    input_device_init();
    lv_indev_drv_init(&indev_drv);
	indev_drv.type = LVGL_INDEV_TYPE;
	indev_drv.read_cb = indev_read_cb;
    input_device = lv_indev_drv_register(&indev_drv);
    // lv_indev_set_group(input_device, groups.g_home);    // 绑定设备和组（触摸屏不需要）

    ESP_LOGI(TAG, "LVGL boot successful");
    return ESP_OK;
}



/**
 * @brief gui刷新线程
 * @param {void} *pvParameters
 * @return {*}
 */
void gui_task(void *pvParameters){
    lvgl_init_demo();
    while (1){
        lv_task_handler();
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}



void app_main(void)
{
    // 创建 gui 任务
    xTaskCreatePinnedToCore(gui_task, "gui", 1024*10, NULL, 1, NULL, 1);
}